/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DateUtil;
import me.zhengjie.business.domain.PricCostDetl;
import me.zhengjie.business.domain.vo.FyxxVo;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.PricCostDetlRepository;
import me.zhengjie.business.service.PricCostDetlService;
import me.zhengjie.business.service.dto.PricCostDetlDto;
import me.zhengjie.business.service.dto.PricCostDetlQueryCriteria;
import me.zhengjie.business.service.mapstruct.PricCostDetlMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2025-01-12
**/
@Service
@RequiredArgsConstructor
public class PricCostDetlServiceImpl implements PricCostDetlService {

    private final PricCostDetlRepository pricCostDetlRepository;
    private final PricCostDetlMapper pricCostDetlMapper;

    private final DeptService deptService;

    @Override
    public Map<String,Object> queryAll(PricCostDetlQueryCriteria criteria, Pageable pageable){
        Page<PricCostDetl> page = pricCostDetlRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(pricCostDetlMapper::toDto));
    }

    @Override
    public List<PricCostDetlDto> queryAll(PricCostDetlQueryCriteria criteria){
        return pricCostDetlMapper.toDto(pricCostDetlRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PricCostDetlDto findById(String pricCostDetlId) {
        PricCostDetl pricCostDetl = pricCostDetlRepository.findById(pricCostDetlId).orElseGet(PricCostDetl::new);
        ValidationUtil.isNull(pricCostDetl.getPricCostDetlId(),"PricCostDetl","pricCostDetlId",pricCostDetlId);
        return pricCostDetlMapper.toDto(pricCostDetl);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PricCostDetlDto create(PricCostDetl resources) {
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));

        String date = DateTimeUtil.getDateTime("yyyyMMdd");


        long currentTimeMillis = System.currentTimeMillis();
        // 创建 Timestamp 对象
        Timestamp timestamp = new Timestamp(currentTimeMillis);

        BigDecimal djBigDecimal = resources.getPric();
        BigDecimal slBigDecimal = resources.getSinCnt();
        BigDecimal zjBigDecimal = djBigDecimal.multiply(slBigDecimal);

        int bcn = (int) ((Math.random() * 9 + 1) * 1000);
        String rgstInsID = resources.getPricRgstInsId();
        String tempid1 = rgstInsID.substring(0, 5).toUpperCase();
        String tempid2 = rgstInsID.substring(0, 20).toUpperCase();



        String LONGTERM_EXE_DETL_CODG = tempid1 + (long)(((Math.random() * 9 + 1) * 1000000000));
        String LONGTERM_PLAN_DETL_CODG = tempid1+(long)((Math.random() * 9 + 1) * 1000000000);
        String LONGTERM_DETL_ID = tempid1+(long)((Math.random() * 9 + 1) * 1000000000);
    //    String LONGTERM_BCHNO = tempid2;
    //    String LONGTERM_TASK_REC_BCHNO = tempid2;
        String LONGTERM_PLAN_DETL_ID = tempid1+(long)((Math.random() * 9 + 1) * 1000000000);


        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);
        resources.setPricCostDetlId(IdUtil.simpleUUID());
        resources.setPricRgstInsId(rgstInsID);
        // 长期护理执行明细编码
        resources.setLongtermExeDetlCodg(LONGTERM_EXE_DETL_CODG);
        resources.setLongtermExeDetlCodg1(LONGTERM_EXE_DETL_CODG);
        // 长期护理计划明细编码
        resources.setLongtermPlanDetlCodg(LONGTERM_PLAN_DETL_CODG);
        // 长期护理明细ID
        resources.setLongtermDetlId(LONGTERM_DETL_ID);
        // 长期护理批次号
        //resources.setLongtermBchno(LONGTERM_BCHNO);
        // 长期护理任务接收批次号
        //resources.setLongtermTaskRecBchno(LONGTERM_TASK_REC_BCHNO);
        // 长期护理计划明细ID
        resources.setLongtermPlanDetlId(LONGTERM_PLAN_DETL_ID);

        // 长期护理明细来源（护理费）
        resources.setLongtermDetlSouc("01");
        // 金额
        resources.setAmt(zjBigDecimal);
        // 明细项目费用总额
        resources.setDetItemFeeSumamt(zjBigDecimal);
        // 护理实际开始时间
        resources.setLongtermActBegntime(timestamp);
        // 护理实际结束时间
        resources.setLongtermActEndtime(timestamp);
        // 护理计划结束时间
        resources.setLongtermPlanEndtime(resources.getLongtermPlanBegntime());
        // 费用发生时间
        resources.setFeeOcurTime(timestamp);

        // 护理机构编号
        resources.setNurscareOrgNo(deptDto.getDeptCode());
        // 护理机构名称
        resources.setNurscareOrgName(deptDto.getDeptName());

        // 医疗目录类别(服务设施)
        resources.setHilistType("3");
        // 医疗类别(机构护理)
        resources.setMedType("990403");

        // 定点归属医保区划
        resources.setFixBlngAdmdvs(resources.getInsuAdmdvs());

        // 机构定价
        resources.setMedinsPric(resources.getPric());
        // 标准定价
        resources.setStdPric(resources.getPric());

        // 开单科室编码
        resources.setBilgDeptCodg(deptDto.getOrgId());
        // 受单科室编码
        resources.setAcordDeptCodg(deptDto.getOrgId());
        // 开单医生编码
        resources.setBilgDrCodg(resources.getNurscarePsnNo());
        // 受单医生编码
        resources.setOrdersDrCode(resources.getNurscarePsnNo());

        // 医院审批标志
        resources.setHospApprFlag("0");

        // 外检标志
        resources.setEtipFlag("0");

        // 出院带药标志
        resources.setDscgTkdrugFlag("0");

        // 组套编号
        resources.setCombNo("1");

        // 护理人员标志(非亲属)
        resources.setNurscarePsnFlag("01");

        resources.setSfsc("0");

        return pricCostDetlMapper.toDto(pricCostDetlRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PricCostDetl resources) {
        PricCostDetl pricCostDetl = pricCostDetlRepository.findById(resources.getPricCostDetlId()).orElseGet(PricCostDetl::new);
        ValidationUtil.isNull( pricCostDetl.getPricCostDetlId(),"PricCostDetl","id",resources.getPricCostDetlId());
        pricCostDetl.copy(resources);
        pricCostDetlRepository.save(pricCostDetl);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String pricCostDetlId : ids) {
            pricCostDetlRepository.deleteById(pricCostDetlId);
        }
    }

    @Override
    public void download(List<PricCostDetlDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PricCostDetlDto pricCostDetl : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> queryPricCostDetl(String rgst_ins_id) {
        List<Object> list = pricCostDetlRepository.queryPricCostDetl(rgst_ins_id);
        Map<String, Object> vo = new HashMap();
        for (Object obj : list) {
            Object[] arr = (Object[]) obj;

            vo.put("zl", arr[0]);
            vo.put("ryrq", arr[1]);
            vo.put("cyrq", arr[2]);
            vo.put("zfy", arr[3]);
            vo.put("wsc", arr[4]);
            vo.put("ysc", arr[5]);
            vo.put("hlsc", arr[6]);
        }
        return vo;
    }
}